import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtDrawer, AtIcon, AtInput, AtList, AtListItem} from 'taro-ui'
import {Picker, Text, View} from '@tarojs/components'
import {http} from '../../../../utils/http'
import {ReverseItem} from '../../../../utils/server.interface'
import {TEAM_APPOINT_PAGE} from '../../../../constants/api'
import {h5Wx} from "../../../../utils/h5.service";
import GzhAuth from "../../../../components/gzh-auth/gzh-auth"
import './list.scss'

export default class List extends Component {
  state: {
    loadMoreStatus: "more" | "loading" | "noMore"
    appointList: ReverseItem[]
    tabIndex: number
    show: boolean
    tabList: any
    queryData: any
  } = {
    queryData: {
      type: 'sitemini',
      search_reserve_date_end: '',
      search_oredrNum: '',
      search_reserve_date_start: '',
      search_status: '',
      search_goods_name: '',
      pageSize: 10,
    },
    loadMoreStatus: 'loading',
    appointList: [],
    tabList: [{title: '全部', value: '', index: 0}, {title: '已接收', value: '1', index: 1}, {
      title: '已拒绝',
      value: '2',
      index: 2
    }, {title: '已完成', value: '3', index: 3}],
    show: false,
    tabIndex: 0,
  }

  onPullDownRefresh() {
    Taro.stopPullDownRefresh()
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const appointList = await this.getData()
    this.setState({appointList})
  }

  page = 1

  async getData() {
    this.state.queryData.page = this.page
    const appointList = await http.carGet(TEAM_APPOINT_PAGE, this.state.queryData)
    appointList.map((item) => {
      if(item.info_item_detail_config) item.info_item_detail_config = JSON.parse(item.info_item_detail_config)
    })
    if (appointList && appointList.length === 10) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    return appointList || []
  }

  onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'}, async () => {
        this.page++
        const appointList = await this.getData()
        const old = this.state.appointList
        this.setState({appointList: [...old, ...appointList]})
      })
    }
  }

  async handleForm(flag) {
    const {queryData} = this.state
    this.page = 1
    queryData['page'] = 1
    if (flag) {
      queryData['search_reserve_date_end'] = ''
      queryData['search_oredrNum'] = ''
      queryData['search_reserve_date_start'] = ''
      queryData['search_goods_name'] = ''
      this.setState({queryData})
      return
    }
    this.onClose()
    const appointList = await this.getData()
    this.setState({appointList})
  }

  async handlerTab(tabIndex, auditType) {
    this.page = 1
    this.state.queryData.search_status = auditType
    this.setState({tabIndex}, async () => {
      const appointList = await this.getData()
      this.setState({appointList})
    })
  }

  onClose() {
    this.setState({show: false})
  }

  handleChange(field, val) {
    if (typeof val === 'object') {
      val = val.detail.value
    }
    const {queryData} = this.state
    queryData[field] = val
    this.setState({queryData})
  }

  onCopy(str) {
    try {
      Taro.setClipboardData({
        data: str
      })
      if (process.env.TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  copy() {
    try {
      Taro.setClipboardData({
        data: '111'
      })
      Taro.showToast({title: '复制成功'})
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  render() {
    const {loadMoreStatus, appointList, tabIndex, tabList, show, queryData} = this.state
    return (
      <View className='my-reverse appoint-list-root'>
        <GzhAuth />
        <View className='tab-header'>
          {tabList.map(item =>
            <View key={item.index} className={`tab-item ${tabIndex === item.index ? 'tab-item-active' : ''}`}
              onClick={this.handlerTab.bind(this, item.index, item.value)}
            >
              <View className='line-title'>
                {item.title}
              </View>
              <View className={`at-tabs_item_underline ${tabIndex === item.index ? 'underline-active' : ''}`} />
            </View>
          )}
          <View className='tab-item-search' onClick={() => {
            this.setState({show: true})
          }}
          >筛选<AtIcon prefixClass='car' size='16' value='iconshaixuan' color='#000' /></View>
        </View>
        <View className='content'>
          {appointList.length > 0 && appointList.map(item =>
            <View className='item'>
              <View className='title-box'>
                <View className='title-box-status'>
                  {item.status === 0 && <Text>待接收</Text>}
                  {item.status === 1 && <Text>已接收</Text>}
                  {item.status === 2 && <Text>已拒绝</Text>}
                  {item.status === 3 && <Text>已完成</Text>}
                </View>
                <View className='title'>
                  <View className={`${process.env.TARO_ENV}`}>{item.goods_name}</View>
                </View>
                <View className='line' />
                <View className='time'>订单号：{item.order_num}</View>
                { item.info_item_detail_config.reserve_date && <View className='time'>预约时间：{item.reserve_date}</View> }
                { item.info_item_detail_config.in_date && <View className='time'>入场时间：{item.inDate}</View> }
                { item.info_item_detail_config.team_org && <View className='time'>组团单位：{item.team_org}</View> }
                { item.info_item_detail_config.linkman && <View className='time'>领队姓名：{item.linkman}</View> }
                { item.info_item_detail_config.link_phone && <View className='time'>领队电话：{item.link_phone}</View> }
                { item.info_item_detail_config.team_address && <View className='time'>客源地：{item.team_address}</View> }
                { item.info_item_detail_config.guide_num && <View className='time'>讲解员人数：{item.guide_num}</View> }
                { item.info_item_detail_config.is_reserve_meal && <View className='time'>是否订餐：{!!item.is_reserve_meal ? '是' : '否'}</View> }
                { item.info_item_detail_config.custom_num && <View className='time'>预约人数：{item.custom_num}</View> }
                {item.status === 3 && <View className='time'>实际人数：{item.real_custom_num}</View>}
                <View className='detail-view'>
                  <View className='detail-btn' onClick={() => {
                    Taro.navigateTo({url: '/page/my/teamappoint/order/detail?orderNum=' + item.order_num + '&orderId=' + item.id + '&page=sitemini&extendPage=site&hiddenBtn=true'})
                  }}
                  >详情</View>
                </View>
              </View>
            </View>
          )}
          {appointList.length <= 0 && <View style='font-size: 16px;text-align:center; padding: 40px 0; color: #aaa;'>您还没有团队预约信息</View>}
        </View>
        <AtDrawer show={show} right mask onClose={this.onClose.bind(this)}>
          <View className='view-m-b'>
            <AtInput name='search_goods_name' title='商品名称' type='text' value={queryData.search_goods_name}
              onChange={this.handleChange.bind(this, 'search_goods_name')}
            />
          </View>
          <View className='view-m-b-order-num'>
            <AtInput name='link_name' title='订单号' type='text' value={queryData.search_oredrNum}
              onChange={this.handleChange.bind(this, 'search_oredrNum')}
            />
          </View>
          <View className='view-m-b-reserve-date'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'search_reserve_date_start')}>
              <AtList>
                <AtListItem title='预订时间起' extraText={queryData.search_reserve_date_start} />
              </AtList>
            </Picker>
          </View>
          <View className='view-m-b view-m-b-reserve-date-end'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'search_reserve_date_end')}>
              <AtList>
                <AtListItem title='预订时间止' extraText={queryData.search_reserve_date_end} />
              </AtList>
            </Picker>
          </View>
          <View className='dialog-footer'>
            <View className='reset' onClick={this.handleForm.bind(this, true)}>重置</View>
            <View className='search' onClick={this.handleForm.bind(this, false)}>搜索</View>
          </View>
        </AtDrawer>
      </View>
    )
  }
}
